<?php
/**
 * Created by PhpStorm.
 * User: another
 * Date: 2019-04-23
 * Time: 16:49
 */
namespace App\Models;

use Zizaco\Entrust\EntrustPermission;

class Permission extends EntrustPermission
{
    /**
     * 可以被批量赋值的属性。
     *
     * @var array
     */
    protected $fillable = [
        'pid','name', 'display_name', 'description','class','character',
    ];


    /**
     * 添加规则
     * @param $data
     * @return mixed
     */
    public function addPermission($data)
    {
        $is_name = $this->getPermission(['name'=>$data['name']],['id']);
        if(!empty($is_name)){
            $resule['code'] = '0';
            $resule['message'] = '此规则已添加';
            return $resule;
        }

        unset($data['user']);

        //1、先插入信息
        //返回新纪录的主键id值
        if(!$id = $this->insertGetId($data)){
            $resule['code'] = '0';
            $resule['message'] = '添加失败，请重新添加';
            return $resule;
        }

        $bool = $this->setPath($data,$id,0);
        if($bool){
            $resule['code'] = '1';
            $resule['message'] = '添加成功';
        }else{
            $resule['code'] = '0';
            $resule['message'] = '添加失败，请重新添加';
        }

        return $resule;
    }


    public function updPermission($data)
    {
        if($data['pid'] == $data['id']){
            $resule['code'] = '0';
            $resule['message'] = '乖乖数据异常';
            return $resule;
        }

        $info = $this->getPermission(['id'=>$data['id']],['id','path']);
        if(empty($info)){
            $resule['code'] = '0';
            $resule['message'] = '乖乖数据异常';
            return $resule;
        }

        $bool = $this->setPath($data,$info->id,1);
        if($bool){
            $resule['code'] = '1';
            $resule['message'] = '修改成功';
        }else{
            $resule['code'] = '0';
            $resule['message'] = '修改失败';
        }

        return $resule;
    }


    public function setPath($data,$id,$type)
    {
        //2、在重新更新path和level
        if($data['pid'] == 0){
            $path = $id;
        }else{
            $pinfo = $this->getPermission(['id'=>$data['pid']],['id','path']);
            if(empty($pinfo)){
                $path = $id;
            }else{
                $path = $pinfo->path.'-'.$id;
            }
        }

        //level数目，全路径里面“-”的个数
        //把全路径变为数组，把数组元素的个数总和减去1
        $temp['level'] = count(explode('-', $path)) -1;
        $temp['path'] = $path;
        if($type == 1){
            $temp['name'] = $data['name'];
            $temp['display_name'] = $data['display_name'];
            $temp['display_name'] = $data['display_name'];
            $temp['pid'] = $data['pid'];
        }

        //3、更新数据
        return $this->where('id',$id)->update($temp);
    }


    public function getPermission($where,$key)
    {
        return $this->where($where)->first($key);
    }
}
